package com.cf.limit.core.service;


import com.cf.crud.service.AbsBaseService;
import com.cf.id.SnowflakeId;
import com.cf.limit.core.dao.BlackMapper;
import com.cf.limit.core.frequency.IpLimitProperty;
import com.cf.limit.core.model.Black;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;

/**
 * game-server-BlackMapperService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/12 下午 05:19
 */
@Slf4j
public class BlackService extends AbsBaseService<Black, BlackMapper> {

    private static final String BLACK_CHECK_PREFIX = "BLACK_CHECK_PREFIX_";

    @Autowired
    private SnowflakeId id;

    @Autowired
    private IpLimitProperty ipLimitProperty;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Class getTargetClass() {
        return Black.class;
    }

    /**
     * 判断一个ip是否是黑名单
     *
     * @param ip
     * @return
     */
    public boolean isBlack(String ip) {
        Black black = this.mapper.selectByIp(ip);
        return black != null;
    }

    /**
     * 判断
     *
     * @param ip
     */
    public void addBlack(String ip) {
        Long increment = redisTemplate.opsForValue().increment(getBlackCheckPrefixKey(ip), 1);
        if (increment == ipLimitProperty.getBlackTimes() + 1) {
            log.info("ip【{}】违反限制访问次数超过阀值，加入黑名单！", ip);
            this.addToBlack(ip);
        } else {
            if (increment < ipLimitProperty.getBlackTimes() + 1)
                log.info("ip【{}】违反限制但还不足以加入黑名单！当前警告次数为【{}】，最大为【{}】", ip, increment, ipLimitProperty.getBlackTimes());
            else
                log.info("ip【{}】违反限制已经加入黑名单", ip, increment, ipLimitProperty.getBlackTimes());
        }
    }

    private void addToBlack(String ip) {
        Black black = new Black();
        black.setBlackTime(new Date());
        black.setIp(ip);
        black.setId(id.nextId());
        this.mapper.insert(black);
    }

    private String getBlackCheckPrefixKey(String ip) {
        return BLACK_CHECK_PREFIX + ip;
    }

}
